package com.wsp.controllermanagement.security;

import com.wsp.apimanagement.pojo.entity.Admin;
import com.wsp.service.mapper.AdministratorMapper;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;

/**
 * Package: com.wsp.controllermanagement.security
 * Description： TODO
 *
 * @Author: 巫思平
 * Copyright: Copyright (c) 2020
 * Version: 1
 */
@DependsOn(
        value = {
                "com.wsp.service.mapper.AdministratorMapper"
        })
public class AdminRealm extends AuthorizingRealm {
    @Autowired
    private AdministratorMapper administratorMapper;

    /**
     * 授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取当前管理员
        Admin admin = (Admin) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRole(admin.getRole());
        return info;
    }

    /**
     * 认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        Admin admin = administratorMapper.queryAdminByCount(token.getUsername());
        if(admin == null){
            return null;
        }
        return new SimpleAuthenticationInfo(admin,admin.getPassword(),null,getName());
    }
}
